package edu.ycu.aladdin.web.controller;

import edu.ycu.aladdin.web.dto.User;
import edu.ycu.aladdin.web.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

import static edu.ycu.aladdin.web.common.OauthChannel.BAI_DU;
import static edu.ycu.aladdin.web.common.OauthChannel.GITHUB;

/**
 * 授权回调.
 * // TODO 防止跨站点请求伪造攻击
 *
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 1.0
 */
@Controller
@RequestMapping("/oauth/callback")
public class OauthCallbackController extends AbsController {

    Logger logger = LoggerFactory.getLogger(AbsController.class);

    private final UserService userService;

    @Autowired
    public OauthCallbackController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/baidu")
    @ResponseBody
    public String baiduOauth(@RequestParam("code") String code, HttpServletResponse response) {

        User user = userService.login(BAI_DU, code);
        setLoginCookie(user.getUid(), response);
        setCookie(COOKIE_OAUTH_CHANNLE, BAI_DU.name(), response);

        return REDIRECT_INDEX;
    }

    @RequestMapping("/github")
    @ResponseBody
    public String githubOauth(@RequestParam("code") String code, @RequestParam("state") String state, HttpServletResponse response) {

        User user = userService.login(GITHUB, code);
        setLoginCookie(user.getUid(), response);
        setCookie(COOKIE_OAUTH_CHANNLE, GITHUB.name(), response);

        return REDIRECT_INDEX;
    }

    // TODO 其他三方平台授权回调
    @RequestMapping("/weibo")
    public void weiboOauth() {

    }

    @RequestMapping("/csdn")
    public void csdnOauth() {

    }

    @RequestMapping("/weichat")
    public void weichatOauth() {

    }

    @RequestMapping("/dingtalk")
    public void dingtalkOauth() {

    }
}
